package org.cid54.jshopper.controller;

import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfCell;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import javax.servlet.http.HttpServletResponse;
import org.cid54.jshopper.model.ShopItem;
import org.cid54.jshopper.model.ShoppingList;
import org.cid54.jshopper.service.ShoppingListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author fgo
 */
@Controller
@RequestMapping(value = "pdf")
public class PDFController {

    @Autowired
    private ShoppingListService shoppingListService;

    @RequestMapping(method = RequestMethod.GET, value = "shoppingList/{id}")
    public void doShoppingListPdf(@PathVariable("id") long shoppingListId, HttpServletResponse response) throws Exception {

        ShoppingList shoppingList = this.shoppingListService.getShoppingListById(shoppingListId);

        Document d = new Document(PageSize.A4, 50, 50, 50, 50);

        PdfWriter.getInstance(d, response.getOutputStream());

        d.open();

        Paragraph p = new Paragraph(shoppingList.getName());

        float[] colsWidth = {3.0F, 1.0F};

        PdfPTable table = new PdfPTable(colsWidth);

        table.getDefaultCell().setBorder(0);

        for (ShopItem shopItem : shoppingList.getShopItems()) {

            table.addCell(shopItem.getItem().getName());

            PdfPCell cell = new PdfPCell(new Phrase(shopItem.getAmount() + "x"));
            cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cell.setBorder(0);
            table.addCell(cell);

        }

        p.add(table);

        d.add(p);

        d.close();

    }
}
